import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormGroup } from "@angular/forms";
import { NzMessageService, NzModalService } from "ng-zorro-antd";
import { DataReportService } from "../service/http/date-report.service";
import { ActivatedRoute, Router } from "@angular/router";
import { format, startOfDay, startOfHour, subDays, subHours } from "date-fns";
import { AlarmType, EventName, IP, Port, Protocol } from "../service/mockConst";

@Component({
  selector: "app-base-use",
  templateUrl: "./base-use.component.html",
  styleUrls: ["./base-use.component.less"],
})
export class BaseUseComponent implements OnInit {
  params: any;
  searchForm: FormGroup;
  reportStatusOption = [
    { value: 1, label: "未上报" },
    { value: 2, label: "上报成功" },
    { value: 3, label: "上报失败" },
  ];
  levelOption = [
    { value: 1, label: "低" },
    { value: 2, label: "中" },
    { value: 3, label: "高" },
  ];
  dataList = [];
  total = 0;
  loading = false;
  pageIndex = 1;
  pageSize = 10;
  isAllChecked = false;
  // 是否选择一页
  isOnePageChecked = false;
  // 待处置列表
  disposing: { map: { [props: string]: boolean }; length: number } = {
    map: {},
    length: 0,
  };
  // 单页是否半选
  isOnePageIndeterminate = false;
  // 初始时间
  dateTimeOptions: any = {
    // key: "last_7_days",
    key: "clear_time",
    lineBreak: true,
    cssClass: "has-border",
  };
  quickModeOptions = [
    "last_24_hours",
    "last_3_days",
    "last_7_days",
    "last_30_days",
    "clear_time",
  ];
  timeRange = {
    start_time: subDays(startOfDay(new Date()), 7),
    end_time: new Date(),
  };
  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private modalService: NzModalService,
    private router: Router,
    private http: DataReportService,
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    this.initSearchForm();
    this.route.queryParams.subscribe((params) => {
      this.searchForm.patchValue({
        reportStatus: Number(params.reportStatus),
        eventName: params.eventName,
        warnLevel: Number(params.warnLevel),
      });
    });
    this.getList();
  }

  initSearchForm() {
    this.searchForm = this.fb.group({
      reportStatus: [],
      eventName: [],
      warnLevel: [],
    });
    this.timeRange = {
      start_time: null,
      end_time: null,
    };
  }

  resetForm() {
    this.searchForm.reset();
  }

  checkedAllChange(e): void {
    this.isAllChecked = e;
  }

  checkedOnePageChange(e): void {
    this.dataList.forEach((item) => {
      this.disposing.map[item.id] = e;
    });
    this.disposing.length = e ? Object.keys(this.disposing.map).length : 0;
    if (e) {
      this.isOnePageChecked = e;
      this.isOnePageIndeterminate = !e;
    } else {
      this.disposing.map = {};
      this.isOnePageIndeterminate = e;
    }
  }

  checkedOneChange(data, e): void {
    this.disposing.map[data.id] = e;
    this.disposing.length = Object.values(this.disposing.map).filter(
      (value) => value === true
    ).length;
    const ids = this.dataList.map((item) => this.disposing.map[item.id]);
    const allForTruly = ids.every((item) => item);
    const someForTruly = ids.some((item) => item);
    if (allForTruly) {
      // 如果当前列表的id全为true
      this.isOnePageChecked = true;
      this.isOnePageIndeterminate = false;
    } else if (someForTruly) {
      // 如果当前列表的id全不为true
      this.isOnePageChecked = false;
      this.isOnePageIndeterminate = true;
    } else {
      this.isOnePageChecked = false;
      this.isOnePageIndeterminate = false;
    }
  }

  pageChange(number, type) {
    if (type === "page") {
      this.pageIndex = number;
      if (this.params) {
        this.params.page = number;
      }
    } else {
      this.pageSize = number;
      this.pageIndex = 1;
      if (this.params) {
        this.params.page_size = number;
      }
    }
    this.getList(this.params);
  }

  //获取列表数据
  getList(data?) {
    this.loading = true;
    this.dataList = [];
    console.log(151, this.searchForm.get("warnLevel").value);
    const params = {
      page: data && data === "new" ? 1 : this.pageIndex,
      page_size: data && data === "new" ? 10 : this.pageSize,
      event_name: this.searchForm.get("eventName").value,
      report_status: this.searchForm.get("reportStatus").value,
      alarm_level:
        this.searchForm.get("warnLevel").value &&
        this.searchForm
          .get("warnLevel")
          .value.filter((item) => !Number.isNaN(item)),
      // 当前node后端支持时间戳start_time:1752559200000和格式化时间start_time: "2025-07-15 14:00:00"两种查询方式
      // start_time: this.timeRange.start_time
      //   ? format(this.timeRange.start_time, "YYYY-MM-DD HH:mm:ss")
      //   : null,
      // end_time: this.timeRange.end_time
      //   ? format(this.timeRange.end_time, "YYYY-MM-DD HH:mm:ss")
      //   : null,
      start_time: this.timeRange.start_time
        ? this.timeRange.start_time.getTime()
        : null,
      end_time: this.timeRange.end_time
        ? this.timeRange.end_time.getTime()
        : null,
    };
    this.http.getListData(params).subscribe(
      (res) => {
        if (res.status === 200) {
          this.dataList = res.result;
          this.total = res.total || 0;
        } else {
          this.message.error(res.message);
        }
        this.loading = false;
      },
      (error) => {
        this.loading = false;
        this.message.error("数据获取异常");
      }
    );
  }

  batchDeletion(status) {
    let ids = Object.keys(this.disposing.map).filter(
      (item) => this.disposing.map[item]
    );
    this.placeAndClose(ids, this.isAllChecked, status);
  }

  onDeleteItem(data) {
    this.total--; // 删除一条数据

    const totalPages = Math.ceil(this.total / this.pageSize);

    // 如果当前页码大于总页数，则跳到最后一页（可能是上一页）
    if (this.pageIndex > totalPages) {
      this.pageIndex = totalPages;
    }

    // 如果总页数为0（所有数据都被删完了），则强制回到第一页
    if (totalPages === 0) {
      this.pageIndex = 1;
    }

    this.getList(data); // 刷新数据
  }

  placeAndClose(id, all, status) {
    // status:1上报，2删除
    const params = {
      action: status,
      id_list: all ? "all" : Array.isArray(id) ? id : [id],
      event_name: this.searchForm.get("eventName").value,
      report_status: this.searchForm.get("reportStatus").value,
      alarm_level:
        this.searchForm.get("warnLevel").value &&
        this.searchForm
          .get("warnLevel")
          .value.filter((item) => !Number.isNaN(item)),
      start_time: this.timeRange.start_time
        ? format(this.timeRange.start_time, "YYYY-MM-DD HH:mm:ss")
        : null,
      end_time: this.timeRange.end_time
        ? format(this.timeRange.end_time, "YYYY-MM-DD HH:mm:ss")
        : null,
    };
    this.http.reportDataAction(params).subscribe(
      (res) => {
        this.isAllChecked = false;
        if (res.status === 200) {
          this.message.success(res.msg);
          this.pageIndex = 1;
          this.pageSize = 10;
          this.disposing.map = {};
          this.disposing.length = 0;
          this.isOnePageIndeterminate = false;
          this.isOnePageChecked = false;
          this.getList(this.params);
        } else {
          this.message.error(res.msg);
          // this.pageIndex = 1;
          // this.pageSize = 10;
          this.getList(this.params);
        }
      },
      (error) => {
        this.message.error("处理失败！");
      }
    );
  }

  timeChangeFunc(e) {
    this.timeRange.start_time = e.startTime;
    this.timeRange.end_time = e.endTime;
  }

  goToDetail(data) {
    // let url = `/WebApi/business_common_service/static/dist/#/judge-operation/route/event/details?id=${data.id}&start_time=${data.start_time}&end_time=${data.end_time}`
    let url = `/WebApi/business_common_service/static/dist/#/judge-operation/route/event/details?id=${data.id}`;
    window.open(url, "_blank");
  }

  addData() {
    let eventName = EventName;
    let ip = IP;
    let alarmType = AlarmType;
    let port = Port;
    let protocol = Protocol;
    const params = {
      event_name: eventName[Math.round(Math.random() * eventName.length) + 1],
      alarm_level: Math.round(Math.random() * 2) + 1,
      alarm_type: alarmType[Math.round(Math.random() * alarmType.length) + 1],
      source_ip: ip[Math.round(Math.random() * ip.length) + 1],
      source_port: port[Math.round(Math.random() * port.length) + 1],
      destination_ip: ip[Math.round(Math.random() * ip.length) + 1],
      destination_port: port[Math.round(Math.random() * port.length) + 1],
      protocol: protocol[Math.round(Math.random() * protocol.length) + 1],
      direction: ["入站", "出站"][Math.round(Math.random() * 2)],
      report_status: Math.round(Math.random() * 2) + 1,
      report_time: new Date().getTime(),
    };
    this.http.addData(params).subscribe(
      (res) => {
        if (res.status === 200) {
          this.message.success(res.message);
          this.getList(this.params);
        } else {
          this.message.error(res.message);
        }
      },
      (error) => {
        this.message.error("新增失败！");
      }
    );
  }
}
